package me.seawenc.datastash.outputs.jdbc.helper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * sql执行器
 */
public class SqlActuator {
    String jdbcPath;
    String username;
    String password;
    String driver;

    protected Connection jdbcConn;

    //连续出错3次，重新建立连接
    int errorNum=0;
    /**
     * 初始化数据库连接
     * @param driver
     */
    public SqlActuator(String jdbcPath,String username,String password, String driver) {
        this.jdbcPath=jdbcPath;
        this.username=username;
        this.password=password;
        this.driver =driver;
        getConnection();
    }

    private Connection getConnection()  {
        if(jdbcConn!=null){
            return jdbcConn;
        }
        Properties properties = new Properties();
        properties.setProperty("user", username);
        properties.setProperty("password", password);
        try {
            Class.forName(driver);
            jdbcConn = DriverManager.getConnection(jdbcPath, properties);
        } catch (Exception throwables) {
            System.out.println("获得jdbc连接失败!,msg:" + throwables.getMessage());
        }
        return jdbcConn;
    }

    /**
     * 执行查询sql
     * @param sql
     * @return
     * @throws SQLException
     */
    public void execInsert(String sql) throws Exception {
        //过滤掉注释，去掉换行
        sql=Arrays.stream(sql.split("\n")).filter(v-> !v.startsWith("--")).collect(Collectors.joining(" "));
        PreparedStatement p=null;
        System.out.println("开始执行sql:"+sql);
        try {
            p = getConnection().prepareStatement(sql);
            p.execute();
            errorNum=0;
        } catch (SQLException e) {
            errorNum++;
            if(errorNum>3){
                try{
                    this.jdbcConn.close();
                } catch (SQLException ex) {
                }finally {
                    this.jdbcConn=null;
                }
            }
            throw new RuntimeException(e);
        }finally {
            // 关闭连接和释放资源
            try {
                if (p != null)  p.close();
            } catch (SQLException e) {
            }
        }
    }

    public void close() throws SQLException {
        if(jdbcConn!=null){
            jdbcConn.close();
        }
    }
}
